"""

    Lamptop development utilities
    Copyright (C) 2011  Colby T. Sollars

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
"""

from base import lamptopCliAction_base
import lamptop_util
import getpass

class lamptopCliAction_database(lamptopCliAction_base):
    db_name = ""
    db_user = ""
    db_pass = ""
    def __init__(self):
        lamptopCliAction_base.__init__(self)
        self.db_util = lamptop_util.lamptopDatabase()
        
    def do_action(self, subcommand="", options=[]):
        lamptopCliAction_base.do_action(self, subcommand)
        
        if subcommand == "create":
            return self._create_database()
        elif subcommand == "drop":
            return self._drop_database()
    
    def db_connect(self):
        root_pw = getpass.unix_getpass("MySql root password: ")
        connect_success = self.db_util.connect("root", root_pw)
        while not connect_success:
            print "WHOOPS! Couldn't connect to MySql."
            try_again = raw_input("Would you like to try again? [y]: ")
            if try_again in ["n", "N"]:
                return False
            root_pw = getpass.unix_getpass("MySql root password: ")
            connect_success = self.db_util.connect("root", root_pw)
        return True
    
    def _create_database(self):
        errors = []
        if not self.db_connect():
            errors.append("Failed to connect to database. Operation aborted")
            return errors
        
        self.db_name = self._get_validated_input(
            "Database Name: ", \
            "WHOOPS! The database name you entered won't work for the following reasons:",
            self.db_util.validate_new_db_name)
        self.db_user = self._get_validated_input(
            "Database Username: ", \
            "WHOOPS! The username you entered won't work for the following reasons:",
            self.db_util.validate_new_db_username)
        self.db_pass = raw_input("Database Password: ")
        
        errors = self.db_util.create_database(self.db_name, self.db_user, self.db_pass)
        self.db_util.close()
        return errors
    
    def _drop_database(self):
        errors = []
        db_name = ""
        if len(self.options) > 0:
            db_name = self.options[0]
        if not db_name:
            db_name = raw_input("Database name: ")
        do_drop = True
        if not self.force:
            do_drop_str = raw_input("Are you sure you want to drop database '%s'? [y]: " % db_name)
            if do_drop_str in ["n", "N"]:
                errors.append("Database drop aborted")
                return errors
        
        if not self.db_connect():
            errors.append("Failed to connect to database. Operation aborted")
            return errors
        
        db_exists = self.db_util.db_exists(db_name)
        while not db_exists:
            print "Database name '%s' does not exist" % db_name
            db_name = raw_input("Database name: ")
            db_exists = self.db_util.db_exists(db_name)
        
        return self.db_util.drop_database(db_name)
    
    def failure_message(self, errors):
        lamptopCliAction_base.failure_message(self, errors)
        message = "Failed."
        if self.subcommand == "create":
            message = "WHOOPS! Failed to create new database for the following reasons:"
        elif self.subcommand == "drop":
            message = "WHOOPS! Failed to drop database for the following reasons:"
        print message
        for err in errors:
            print "    " + err
    
    def success_message(self):
        lamptopCliAction_base.success_message(self)
        message = "Success."
        if self.subcommand == "create":
            message = "\nNew database successfully created. Log into it with the following command:"
            message+= "mysql %s -u %s -p%s" % (self.db_name, self.db_user, self.db_pass)
        elif self.subcommand == "drop":
            message = "\nDatabase successfully dropped"
        
        print message

    def show_help(self):
        print "usage: lamptop database [subcommand]\n"
        print "Subcommand list:"
        print "  create\t\tCreates a new MySql database"
        print "  drop [database_name]\tDrops the specified database. Asks for database name if none provided."
        print "\nOptional arguments:"
        print "  --force\tWill drop the specified database without confirming."
